import asyncio
import threading
import time

from .neo4j_driver import AsyncNeoGitDriver
from .scanner import GitRepoScanner


class NeoGraphCreator:
    def __init__(
            self,
            url: str,
            port: int,
            username: str,
            passwd: str,
            git_path: str,
            neo4j_database: str = "neo4j"
    ):
        self._scanner = GitRepoScanner(git_path)
        self._neo_driver = AsyncNeoGitDriver(url, port, username, passwd)
        self._neo_database = neo4j_database

        self._db_stop_flag = False
        self._loop = asyncio.new_event_loop()
        self._db_thread = threading.Thread(target=self._loop.run_until_complete, args=(self._wait(), ))
        self._db_thread.start()

    async def _wait(self):
        try:
            await self._neo_driver.verify()
            while not self._db_stop_flag:
                await asyncio.sleep(1)
        finally:
            all_tasks = [t for t in asyncio.all_tasks()
                         if t is not asyncio.current_task()]
            if all_tasks:
                await asyncio.gather(*all_tasks)
            await self._neo_driver.close()

    def stop(self):
        self._db_stop_flag = True

    def create_graph(self):
        for branch_info in self._scanner.get_all_branch():
            asyncio.run_coroutine_threadsafe(
                self._neo_driver.create_branch_node(
                    self._neo_database,
                    self._scanner.repo_name,
                    **branch_info
                ), self._loop)

        self.stop()
